/**
 * 
 */
package gui.view;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import stubs.ServiceStub;

/**
 * @author Elisa Costante
 * 
 */
public class CartesianServicesTableModel extends DefaultTableModel {

	private static final long serialVersionUID = 6261606106624750773L;

	public void setUpTable(int n, EngineMain frame, boolean fromFile) {

		this.setColumnCount(n + 1);
		this.setRowCount(n);

		// Set Column Names
		String[] columnNames = new String[n + 1];
		columnNames[0] = "";
		for (int i = 1; i < n + 1; i++) {

			columnNames[i] = "Service" + i;
		}
		this.setColumnIdentifiers(columnNames);

		// Set the first column
		for (int i = 0; i < frame.getMonitoredServices().size(); i++) {
			this.setValueAt(columnNames[i + 1], i, 0);
		}

		for (int i = 0; i < n; i++) {
			for (int k = 1; k < n + 1; k++) {
				if (k == i + 1) {
					// Diagonale Principale

					this.setValueAt(new String("NULL"), i, k);

				} else {
					if (fromFile) {
						String columnName = this.getColumnName(k);
						// read the caller name
						String callerName = (String) this.getValueAt(i, 0);
						ServiceStub caller = (ServiceStub) frame
								.getMonitoredServiceFromName(callerName);
						// read the monitored services from the caller
						if (caller.getMonitoredServices() != null) {
							ServiceStub calle = (ServiceStub) caller
									.getMonitoredService(columnName);
							if (calle != null && calle.getTrustValue() != null) {
								this.setValueAt(calle.getTrustValue()
										.getLabel(), i, k);
							} else {
								this.setValueAt(new String("NULL"), i, k);
							}
						} else {
							this.setValueAt(new String("NULL"), i, k);
						}

					} else
						this.setValueAt(new String("NULL"), i, k);
				}

			}

		}

	}

	@Override
	public boolean isCellEditable(int row, int column) {

		if (column == (row + 1) || (column == 0))
			return false;
		else
			return true;
	}

	public void setUpComboColumn(JTable jtable, JComboBox combo) {

		TableColumn comboColumn;
		for (int i = 1; i < this.columnIdentifiers.size(); i++) {
			comboColumn = jtable.getColumnModel().getColumn(i);
			comboColumn.setCellEditor(new DefaultCellEditor(combo));
		}
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		if (columnIndex == 0)
			return String.class;
		else
			return getValueAt(0, columnIndex).getClass();
	}

}
